import React, {
  ReactElement,
  useLayoutEffect,
  useImperativeHandle,
  useRef,
  forwardRef,
} from 'react';
import * as echarts from 'echarts';
import { throttle } from 'lodash';
import { useMount, useUnmount } from 'ahooks';

function BaseChart(props, ref) {
  const { id, option, style } = props;
  const instance = useRef();

  useImperativeHandle(ref, () => {
    return {
      setOption(opt) {
        if (instance.current) {
          instance.current.setOption(opt);
        }
      },
    };
  });
  useLayoutEffect(() => {
    const el = document.getElementById(id);

    if (el) {
      instance.current = echarts.init(document.getElementById(id), undefined, {
        renderer: 'svg',
      });
      instance.current.setOption(option);
    }
  }, [id, option]);

  const func = throttle(() => {
    if (instance.current) {
      instance.current.resize();
    }
  }, 300);

  useMount(() => {
    window.addEventListener('resize', func);
  });

  useUnmount(() => {
    window.removeEventListener('resize', func);
  })

  return <div id={id} style={style} />;
}

export default forwardRef(BaseChart);
